//给你二叉树的根节点 root ，返回其节点值的 层序遍历 。 （即逐层地，从左到右访问所有节点）。
//
//
//
// 示例 1：
//
//
//输入：root = [3,9,20,null,null,15,7]
//输出：[[3],[9,20],[15,7]]
//
//
// 示例 2：
//
//
//输入：root = [1]
//输出：[[1]]
//
//
// 示例 3：
//
//
//输入：root = []
//输出：[]
//
//
//
//
// 提示：
//
//
// 树中节点数目在范围 [0, 2000] 内
// -1000 <= Node.val <= 1000
//
// Related Topics 树 广度优先搜索 二叉树 👍 1168 👎 0

package leetcode.editor.cn;

import leetcode.editor.cn.tree.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("all")
//Java：二叉树的层序遍历
public class 二叉树的层序遍历 {
    public static void main(String[] args) {
        Solution solution = new 二叉树的层序遍历().new Solution();
        // TO TEST

        TreeNode node1 = new TreeNode(15);
        TreeNode node2 = new TreeNode(7);
        TreeNode node3 = new TreeNode(9);
        TreeNode node4 = new TreeNode(20, node1, node2);
        TreeNode root = new TreeNode(3, node3, node4);

        solution.levelOrder(root);

    }
//leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        private List<List<Integer>> res = new ArrayList<>();
        private ArrayDeque<TreeNode> from = new ArrayDeque<>();
        private ArrayDeque<TreeNode> to = new ArrayDeque<>();

        public List<List<Integer>> levelOrder(TreeNode root) {
            if (root != null)
                traval(root);
            return res;
        }

        private void traval(TreeNode root) {
            from.offer(root);

            while (!from.isEmpty()) {
                List<Integer> layer = new ArrayList<>();
                while (!from.isEmpty()) {
                    TreeNode node = from.poll();
                    if (node.left != null)
                        to.offer(node.left);
                    if (node.right != null)
                        to.offer(node.right);
                    layer.add(node.val);
                }
                res.add(layer);
                ArrayDeque<TreeNode> temp = from;
                from = to;
                to = temp;
            }
        }
    }
//leetcode submit region end(Prohibit modification and deletion)


}
